package me.monster.smarttraffic.tool

import android.app.AlertDialog
import android.content.Context
import androidx.annotation.StringRes
import me.monster.smarttraffic.R

/**
 * @description
 * @author: Created jiangjiwei in 2020-02-09 14:55
 */
class MsgDialog(context: Context) {

    private var builder: AlertDialog.Builder = AlertDialog.Builder(context)
    private lateinit var dialog: AlertDialog

    companion object {
        fun getInstance(context: Context): MsgDialog {
            return MsgDialog(context)
        }
    }

    fun setTittle(resId: Int): MsgDialog {
        builder.setTitle(resId)
        return this
    }

    fun setTittle(title: String): MsgDialog {
        builder.setTitle(title)
        return this
    }

    fun setMessage(resId: Int): MsgDialog {
        builder.setMessage(resId)
        return this
    }

    fun setMessage(@StringRes id: Int, vararg formatArgs: Any): MsgDialog {
        builder.setMessage(StringUtil.getString(id, formatArgs))
        return this
    }

    fun setMessage(message: String): MsgDialog {
        builder.setMessage(message)
        return this
    }

    fun setPositive(
        listener: MsgClickListener,
        text: String = StringUtil.getString(R.string.app_positive) ?: ""
    ): MsgDialog {
        builder.setPositiveButton(text) { _, what ->
            listener.onClick(what)
            dialog.dismiss()
        }
        return this
    }

    fun setPositive(resId: Int, listener: MsgClickListener): MsgDialog {
        builder.setPositiveButton(resId) { _, what ->
            listener.onClick(what)
        }
        return this
    }

    fun setNegative(
        listener: MsgClickListener?,
        text: String = StringUtil.getString(R.string.app_negative) ?: ""
    ): MsgDialog {
        builder.setNegativeButton(text) { _, what ->
            listener?.onClick(what)
            dialog.dismiss()
        }
        return this
    }

    fun setNegative(resId: Int, listener: MsgClickListener): MsgDialog {
        builder.setNegativeButton(resId) { _, what ->
            listener.onClick(what)
        }
        return this
    }

    fun show() {
        dialog = builder.create()
        dialog.show()
    }
}

interface MsgClickListener {
    fun onClick(what: Int)
}